<template>
  <div class="user-content">
    <div class="user-header">
      <div class="search">
        <div class="search-user">
          用户昵称 <el-input v-model="data.searchName" style="width: 240px;height: 30px;" placeholder="请输入用户昵称" />
        </div>
        <div class="search-type">
          用户角色<el-select v-model="data.selectioned" clearable placeholder="全部" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="header-btn">
        <div class="search-btn">
          <el-button type="primary" @click="searchData">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
        </div>
        <div class="removals-btn">
          <el-button type="success" @click="reset">
            <el-icon>
              <CloseBold />
            </el-icon>
            重置
          </el-button>
        </div>
      </div>
    </div>
    <div class="user-middle-btn">
      <el-button type="success" plain @click="increase = true">
        <el-icon>
          <Plus />
        </el-icon>
        新增<el-dialog v-model="increase" title="增加用户信息" width="800" v-if="data.selection.length == 0">
          <User @confirm="confirmList"></User>
        </el-dialog>
      </el-button>
      <el-button type="success" @click="edit = true">
        <el-icon>
          <Edit />
        </el-icon>
        修改<el-dialog destroy-on-close v-model="edit" title="编辑用户信息" width="800" v-if="data.selection.length == 1">
          <User @confirmChange="confirmChangeList" :change="data.selection"></User>
        </el-dialog>
      </el-button>
      <el-button type="danger" @click="deleteList = true">
        <el-icon>
          <Delete />
        </el-icon>
        删除<el-dialog v-model="deleteList" title="删除信息" width="500" v-if="!!data.selection.length">
          <DeleteUser @closeDelete="closeDelete" @confirmDelete="confirmDelete(e)" :deleteData="data.selection">
          </DeleteUser>
        </el-dialog>
      </el-button>
    </div>
    <div class="table-content" style="max-height: 500px; height: 100%; overflow: auto;">
      <el-table :data="data.pageData" height="600" :border="true" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column v-for="item in data.filteredData" :key="item.Comment" :prop="item.Field" :label="item.Comment"
          width="auto">
          <template #default="{ row }">
            <template v-if="item.Field === 'avatar' && item.Field !== 'password'">
              <img :src="row.avatar" style="width: 100px; height: 100px;" />
            </template>

            <template v-if="item.Field === 'created_at'">
              <span>{{ convertISOToCustomFormat(row.created_at) }}</span>
            </template>

            <template v-else-if="item.Field === 'updated_at'">
              <span>{{ convertISOToCustomFormat(row.updated_at) }}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="paging">
      <div class="demo-pagination-block">
        <el-pagination :default-page-size="10" :page-sizes="[10, 20]" layout="total, sizes, prev, pager, next, jumper"
          :total="data.filteredListData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <!-- <User></User> -->

</template>

<script setup>
import { watch, ref, reactive, computed, onMounted, watchEffect } from 'vue';
// import { useUserStore } from '../../store/user.js'
// import { storeToRefs } from 'pinia';
import User from '../../components/user/User.vue'
import { findUser } from '../../api/user.js'
import { ElMessageBox } from 'element-plus'
import DeleteUser from '../../components/DeleteUser.vue'
import { GetUserData, GetUserList } from '../../api/user.js'
import convertISOToCustomFormat from '../../untils/convertTime.js'

// const userStore = useUserStore();
const data = reactive({
  filteredData: [],
  filteredListData: [],
  selection: [],
  pageSize: 10, //10条/页还是20条/页
  currentPage: 1,
  searchName: '',
  selectioned: [],
  pageData: []
});

// 点击修改
const edit = ref(false)
const increase = ref(false)
const deleteList = ref(false)

// 点击确定,关闭弹窗,
const confirmList = () => {
  GetUserList().then(res => {
    console.log(res.data);
    data.filteredListData = res.data
  })
  return increase.value = false
}
const confirmChangeList = () => {
  GetUserList().then(res => {
    console.log(res.data);
    data.filteredListData = res.data
  })
  return edit.value = false
}



// 点击重置，重置搜索选项框
const reset = () => {
  data.searchName = '',
    data.selectioned = ''
}

// 点击搜索，查找数据
const searchData = async () => {
  // console.log(data.searchName, data.selectioned);
  await findUser({
    searchName: data.searchName,
    selectioned: data.selectioned
  }).then(res => {
    data.filteredListData = res.data;
    console.log(data.filteredListData);
    console.log(res);
  })
  // 处理返回的数据

}

// 点击删除


// 删除按钮的确认与取消
const confirmDelete = () => {
  GetUserList().then(res => {
    console.log(res.data);
    data.filteredListData = res.data
  })
  return deleteList.value = false
}
const closeDelete = () => {
  return deleteList.value = false
}


// 得到用户的菜单，与列表信息
onMounted(() => {
  GetUserData().then(res => {
    data.filteredData = res.data.filter(item => item.Field !== 'password'&&item.Field !== 'address_id') //过滤密码
    console.log(res);
  });
  GetUserList().then(res => {
    data.filteredListData = res.data
    console.log(res);
  });
  // 分页
  watchEffect(() => {
    const startIndex = (data.currentPage - 1) * data.pageSize;
    const endIndex = data.currentPage * data.pageSize;
    console.log(startIndex, endIndex);
    data.pageData = data.filteredListData.slice(startIndex, endIndex);
    console.log(data.pageData);
  });
});




// 根据 startIndex 和 endIndex 对 filteredListData 进行切片，得到当前页应该显示的数据。

const options = [
  {
    value: '管理员',
    label: '管理员',
  },
  {
    value: '普通用户',
    label: '普通用户',
  },

];


function handleSizeChange(val) {
  // console.log(val);
  // 下拉选择器改变每页显示条目的数量时,处理页大小变化后的逻辑，比如重新计算当前页的数据等。
  data.pageSize = val;
  data.currentPage = 1;
}
function handleCurrentChange(val) {
  // console.log(val);
  //分页组件中切换当前页码时, 方法通常用来处理切换页码后的逻辑，比如根据新的页码加载对应数据等。
  data.currentPage = val;
}


// 勾选选项框
const handleSelectionChange = (selection, row) => {
  if (selection !== '') {
    data.selection = selection
    console.log('Selected Rows:', selection); // Log the selected rows
  }
  else { }
  // console.log('Selected Row:', row); // Log the selected row
};


// 监听数据的变化
// watchEffect([ data.currentPage, data.pageSize, data.pageData], () => {
//   updateData();
// });


</script>

<style lang="less" scoped>
.user-content {
  padding: 10px;
  border: 1px solid #e0dbdb;
  border-radius: 5px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
  margin: 10px;
}

.user-header {
  height: 50px;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .search,
  .search-user,
  .search-type {
    margin-right: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .header-btn {
    display: flex;

    .search-btn {
      margin-right: 20px;
    }
  }
}

.user-middle-btn {
  margin: 10px 0px 10px 10px;
}
</style>